import { createRouter, createWebHashHistory } from "vue-router";
import store from "../store";
import { isLogin } from "../api/userApi";

const routes = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/home",
    name: "Home",
    component: () => import("@/views/Home.vue"),
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/Login.vue"),
  },
  {
    path: "/reg",
    name: "Reg",
    component: () => import("@/views/Reg.vue"),
  },
  {
    path: "/cart",
    name: "Cart",
    component: () => import("@/views/Cart.vue"),
  },
  {
    path: "/goods/:id",
    name: "Goods",
    props: true,
    component: () => import("@/views/Goods.vue"),
  },
  {
    path: "/:pathMatch(.*)",
    component: () => import("@/views/Error.vue"),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior() {
    return { top: 0 };
  },
});

//鉴权!
router.beforeEach(async (to, from, next) => {
  if (store.state.user.token) {
    let res = await isLogin();
    if (res) {
      store.commit("user/setUser", res.user);
      store.commit("cart/setCart", res.cart);
    }
    if (res && to.fullPath == "/login") {
      router.push({ name: "Home" });
    }
  }
  next();
});

export default router;
